
package com.lm.activemq;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

public class LastIngReceiver {

	public static void main(String[] args) {

		// ConnectionFactory ：连接工厂，JMS 用它创建连接
		ConnectionFactory connectionFactory;
		// Connection ：JMS 客户端到JMS Provider 的连接
		Connection connection = null;
		// Session： 一个发送或接收消息的线程
		Session session;
		// Destination ：消息的目的地;消息发送给谁.
		
		// 消费者，消息接收者
		MessageConsumer consumer;
		connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, "failover:(tcp://localhost:61616,tcp://localhost:61617)");
		try {
			// 构造从工厂得到连接对象
			connection = connectionFactory.createConnection();
			connection.setClientID("lastin"); //持久订阅需要设置这个。
			// 启动
			connection.start();
			// 获取操作连接
			session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
			// 获取session注意参数值xingbo.xu-queue是一个服务器的queue，须在在ActiveMq的console配置
//			Destination destination = session.createTopic("FirstQueue");
//			consumer = session.createConsumer(destination);
			
			Topic topic = session.createTopic("FirstQueue"); //Topic持久订阅
			consumer = session.createDurableSubscriber(topic,"lastin");
			//listener异步 方式  
		    consumer.setMessageListener(new MessageListener() {  
		 
		        public void onMessage(Message msg) {  
		        	TextMessage message = (TextMessage) msg;
					if (null != message) {
						try {
							System.out.println("2收到消息" + message.getText());
						}
						catch (JMSException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
		        }  
		 
		    });  
		    Thread.sleep(30000);  
		    
//			consumer=session.createConsumer(new Listener());
//			while (true) {
//				// 设置接收者接收消息的时间，为了便于测试，这里谁定为100s
//				TextMessage message = (TextMessage) consumer.receive(500000);
//				if (null != message) {
//					System.out.println("1收到消息" + message.getText());
//				}
//				else {
//					break;
//				}
//			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			try {
				if (null != connection)
					connection.close();
			}
			catch (Throwable ignore) {
			}
		}
	}
}
